package com.nameless.util;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * 自定义元数据对象处理器
 *
 * @author 太阳偷渡青山
 * @date 2022/11/18
 */
@Component
@Slf4j
public class MyMetaObjecthandler implements MetaObjectHandler {

    /**
     * 插入操作，自动填充
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("公共字段自动填充[insert]...");
        log.info(metaObject.toString());

        HttpServletRequest request = WebUtils.getRequest();
        String token = request.getHeader("token");
        Map<String, Object> map = JwtUtil.getTokenChaim(token);
        String username = (String) map.get("username");

        metaObject.setValue("createTime",new Date());
        metaObject.setValue("updateTime",new Date());
        metaObject.setValue("createBy",username);
        metaObject.setValue("updateBy",username);
    }

    /**
     * 更新操作，自动填充
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("公共字段自动填充[update]...");
        log.info(metaObject.toString());

        HttpServletRequest request = WebUtils.getRequest();
        String token = request.getHeader("token");
        Map<String, Object> map = JwtUtil.getTokenChaim(token);
        String  username = (String) map.get("username");

//        long id = Thread.currentThread().getId();
//        log.info("线程id为：{}",id);

        metaObject.setValue("updateTime",new Date());
        metaObject.setValue("updateBy",username);
    }
}
